package com.xxx.lib.ui.widget

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import java.lang.ref.WeakReference

/**
 * 倒计时控件
 */
class CountDownButton(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {

    companion object {
        /**
         * 倒计时
         */
        private var countTime = 0

        /**
         * 开始计时器
         * @param second 倒计时（秒）
         * @param textView 弱引用
         */
        private fun startCountDown(second: Int, textView: WeakReference<AppCompatTextView>?) {
            object : CountDownTimer(second * 1000L, 1000L) {
                override fun onTick(tick: Long) {
                    countTime = (tick / 1000).toInt() + 1
                    setButtonHint(
                        countTime,
                        textView
                    )
                }

                override fun onFinish() {
                    countTime = 0
                    setButtonHint(
                        0,
                        textView
                    )
                }
            }.start()
        }

        /**
         * 设置按钮提示
         *  @param countTime 倒计时（秒）
         * @param textView 弱引用
         */
        private fun setButtonHint(countTime: Int, textView: WeakReference<AppCompatTextView>?) {
            try {
                if (countTime < 1) {
                    textView?.get()?.isEnabled = true
                    textView?.get()?.text = "重新获取"
                } else {
                    textView?.get()?.isEnabled = false
                    textView?.get()?.text = "${countTime}s"
                }
            } catch (e: Exception) {
                textView?.get()?.isEnabled = true
                textView?.get()?.text = "重新获取"
            }
        }

    }


    /**
     * textView弱引用
     */
    private var textView: WeakReference<AppCompatTextView>? = null


    init {
        textView = WeakReference(this)
        if (countTime > 1) {
            setCountDown(countTime)
        }
    }


    /**
     * 设置倒计时
     * @param second 倒计时（秒）
     */
    fun setCountDown(second: Int) {
        startCountDown(
            second,
            textView
        )
    }

}
